using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using HuaRongDaoGame.Models;
using HuaRongDaoGame.Services;
using System.Linq; // Added for .FirstOrDefault()
using System.Text; // Added for StringBuilder

namespace HuaRongDaoGame.Forms
{


    /// <summary>
    /// 游戏主界面窗体
    /// </summary>
    public partial class GameForm : Form
    {
        private GameState gameState;
        private GameBoardRenderer boardRenderer;
        private Timer gameTimer;
        private Timer focusTimer; // 焦点管理定时器
        private Timer demoTimer; // 自动演示定时器
        private bool isDragging = false;
        private Point dragStart;
        private Block draggedBlock = null;
        private List<MoveStep> demoSteps; // 演示步骤
        private int currentDemoStep; // 当前演示步骤
        private bool isDemoRunning; // 是否正在演示

        public GameForm(GameState gameState)
        {
            this.gameState = gameState;
            
            // 立即设置键盘事件
            this.KeyPreview = true;
            this.KeyDown += GameForm_KeyDown;
            
            InitializeGameForm();
        }

        /// <summary>
        /// 初始化游戏窗体
        /// </summary>
        private void InitializeGameForm()
        {
            this.Text = string.Format("华容道游戏 - {0}", gameState.CurrentLayout != null ? gameState.CurrentLayout.Name : "未知布局");
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.Size = new Size(800, 600);
            this.MinimumSize = new Size(700, 500);
            this.BackColor = Color.LightGray;

            // 创建游戏棋盘渲染器
            boardRenderer = new GameBoardRenderer(gameState.GameBoard);
            boardRenderer.Location = new Point(20, 20);
            boardRenderer.Size = new Size(400, 500);
            boardRenderer.Anchor = AnchorStyles.Top | AnchorStyles.Left;

            // 创建游戏计时器
            gameTimer = new Timer();
            gameTimer.Interval = 1000; // 1秒更新一次
            gameTimer.Tick += GameTimer_Tick;
            gameTimer.Start();

            // 创建焦点管理定时器 - 暂时禁用，改为在按钮点击后手动管理焦点
            // focusTimer = new Timer();
            // focusTimer.Interval = 100; // 100毫秒检查一次
            // focusTimer.Tick += FocusTimer_Tick;
            // focusTimer.Start();

            // 创建界面控件
            CreateControls();

            // 注册事件
            gameState.StateChanged += GameState_StateChanged;

            // 开始游戏
            UpdateDisplay();
            
            // 确保游戏状态为Playing
            if (gameState.Status != GameStatus.Playing)
            {
                Console.WriteLine("强制设置游戏状态为Playing");
                gameState.Status = GameStatus.Playing;
            }
            
            // 确保窗体获得焦点
            this.Load += GameForm_Load;
        }

        /// <summary>
        /// 创建界面控件
        /// </summary>
        private void CreateControls()
        {
            // 设置窗体为可接收键盘焦点
            this.TabStop = true;
            this.Focus();
            
            // 游戏信息面板
            var infoPanel = new Panel
            {
                Location = new Point(440, 20),
                Size = new Size(250, 200),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Right
            };

            // 布局名称标签
            var layoutLabel = new Label
            {
                Text = string.Format("布局: {0}", gameState.CurrentLayout != null ? gameState.CurrentLayout.Name : "未知"),
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                Location = new Point(10, 10),
                Size = new Size(230, 20)
            };

            // 步数标签
            var moveCountLabel = new Label
            {
                Name = "moveCountLabel",
                Text = "步数: 0",
                Font = new Font("微软雅黑", 10),
                Location = new Point(10, 40),
                Size = new Size(230, 20)
            };

            // 时间标签
            var timeLabel = new Label
            {
                Name = "timeLabel",
                Text = "时间: 00:00:00",
                Font = new Font("微软雅黑", 10),
                Location = new Point(10, 70),
                Size = new Size(230, 20)
            };

            // 提示次数标签
            var hintLabel = new Label
            {
                Name = "hintLabel",
                Text = string.Format("提示: 0/{0}", gameState.MaxHints),
                Font = new Font("微软雅黑", 10),
                Location = new Point(10, 100),
                Size = new Size(230, 20)
            };

            // 状态标签
            var statusLabel = new Label
            {
                Name = "statusLabel",
                Text = "状态: 游戏中",
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                Location = new Point(10, 130),
                Size = new Size(230, 20)
            };

            // 添加信息控件
            infoPanel.Controls.AddRange(new Control[]
            {
                layoutLabel,
                moveCountLabel,
                timeLabel,
                hintLabel,
                statusLabel
            });

            // 控制按钮面板
            var controlPanel = new Panel
            {
                Location = new Point(440, 240),
                Size = new Size(250, 320),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Right
            };

            // 暂停/继续按钮
            var pauseButton = new Button
            {
                Name = "pauseButton",
                Text = "暂停",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(10, 10),
                BackColor = Color.LightYellow,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            pauseButton.Click += PauseButton_Click;

            // 重新开始按钮
            var restartButton = new Button
            {
                Text = "重新开始",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(120, 10),
                BackColor = Color.LightGreen,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            restartButton.Click += RestartButton_Click;

            // 撤销按钮
            var undoButton = new Button
            {
                Text = "撤销",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(10, 55),
                BackColor = Color.LightBlue,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            undoButton.Click += UndoButton_Click;

            // 提示按钮
            var hintButton = new Button
            {
                Text = "提示",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(120, 55),
                BackColor = Color.LightPink,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            hintButton.Click += HintButton_Click;

            // 保存按钮
            var saveButton = new Button
            {
                Text = "保存游戏",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(10, 100),
                BackColor = Color.LightCyan,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            saveButton.Click += SaveButton_Click;

            // 返回主菜单按钮
            var menuButton = new Button
            {
                Text = "返回主菜单",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(120, 100),
                BackColor = Color.LightCoral,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            menuButton.Click += MenuButton_Click;

            // 方向键按钮
            var upButton = new Button
            {
                Name = "upButton",
                Text = "↑",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Size = new Size(40, 40),
                Location = new Point(85, 150),
                BackColor = Color.LightYellow,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            upButton.Click += (s, e) => MoveSelectedBlock(0, -1);

            var leftButton = new Button
            {
                Name = "leftButton",
                Text = "←",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Size = new Size(40, 40),
                Location = new Point(40, 195),
                BackColor = Color.LightYellow,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            leftButton.Click += (s, e) => MoveSelectedBlock(-1, 0);

            var rightButton = new Button
            {
                Name = "rightButton",
                Text = "→",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Size = new Size(40, 40),
                Location = new Point(130, 195),
                BackColor = Color.LightYellow,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            rightButton.Click += (s, e) => MoveSelectedBlock(1, 0);

            var downButton = new Button
            {
                Name = "downButton",
                Text = "↓",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Size = new Size(40, 40),
                Location = new Point(85, 195),
                BackColor = Color.LightYellow,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            downButton.Click += (s, e) => MoveSelectedBlock(0, 1);

            // 自动演示按钮
            var demoButton = new Button
            {
                Name = "demoButton",
                Text = "自动演示",
                Font = new Font("微软雅黑", 10),
                Size = new Size(100, 35),
                Location = new Point(75, 250),
                BackColor = Color.LightGoldenrodYellow,
                FlatStyle = FlatStyle.Flat,
                TabStop = false
            };
            demoButton.Click += DemoButton_Click;

            // 添加控制按钮
            controlPanel.Controls.AddRange(new Control[]
            {
                pauseButton,
                restartButton,
                undoButton,
                hintButton,
                saveButton,
                menuButton,
                upButton,
                leftButton,
                rightButton,
                downButton,
                demoButton
            });

            // 添加主要控件到窗体
            this.Controls.AddRange(new Control[]
            {
                boardRenderer,
                infoPanel,
                controlPanel
            });
            
            //// 添加测试按钮
            //var testButton = new Button
            //{
            //    Text = "测试键盘",
            //    Location = new Point(440, 540),
            //    Size = new Size(100, 30),
            //    TabStop = false,
            //    Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            //};
            //testButton.Click += (s, e) => 
            //{
            //    Console.WriteLine("测试按钮点击，当前焦点: " + this.Focused);
            //    this.Focus();
            //    MessageBox.Show("请按空格键或方向键测试键盘事件", "测试", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //};
            //this.Controls.Add(testButton);

            // 设置激活事件
            this.Activated += GameForm_Activated;
            
            // 设置窗口大小改变事件
            this.Resize += GameForm_Resize;
            
            // 确保窗体能够接收键盘事件
            Console.WriteLine("键盘事件设置完成");
        }

        /// <summary>
        /// 游戏计时器事件
        /// </summary>
        private void GameTimer_Tick(object sender, EventArgs e)
        {
            UpdateDisplay();
        }

        /// <summary>
        /// 焦点管理定时器事件
        /// </summary>
        private void FocusTimer_Tick(object sender, EventArgs e)
        {
            // 只在没有键盘输入时管理焦点
            // 如果当前焦点在按钮上，暂时不强制转移焦点
            if (this.ActiveControl != null && this.ActiveControl != this)
            {
                // 检查是否是按钮控件
                if (this.ActiveControl is Button)
                {
                    // 如果是按钮，延迟一点时间再转移焦点，让按钮能够响应点击
                    Timer delayTimer = new Timer();
                    delayTimer.Interval = 50; // 50毫秒延迟
                    delayTimer.Tick += (s, args) =>
                    {
                        this.Focus();
                        delayTimer.Stop();
                        delayTimer.Dispose();
                    };
                    delayTimer.Start();
                }
                else
                {
                    // 如果不是按钮，立即转移焦点
                    this.Focus();
                }
            }
        }

        /// <summary>
        /// 游戏状态改变事件
        /// </summary>
        private void GameState_StateChanged(object sender, GameStateChangedEventArgs e)
        {
            UpdateDisplay();
            
            // 检查游戏是否结束
            if (e.GameState.IsGameOver())
            {
                gameTimer.Stop();
                ShowGameResult();
            }
        }

        /// <summary>
        /// 更新显示
        /// </summary>
        private void UpdateDisplay()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(UpdateDisplay));
                return;
            }

            // 更新步数
            var moveCountLabel = this.Controls.Find("moveCountLabel", true).FirstOrDefault() as Label;
            if (moveCountLabel != null)
            {
                moveCountLabel.Text = string.Format("步数: {0}", gameState.MoveCount);
            }

            // 更新时间
            var timeLabel = this.Controls.Find("timeLabel", true).FirstOrDefault() as Label;
            if (timeLabel != null)
            {
                timeLabel.Text = string.Format("时间: {0}", gameState.GetFormattedTime());
            }

            // 更新提示次数
            var hintLabel = this.Controls.Find("hintLabel", true).FirstOrDefault() as Label;
            if (hintLabel != null)
            {
                hintLabel.Text = string.Format("提示: {0}/{1}", gameState.HintCount, gameState.MaxHints);
            }

            // 更新状态
            var statusLabel = this.Controls.Find("statusLabel", true).FirstOrDefault() as Label;
            if (statusLabel != null)
            {
                statusLabel.Text = string.Format("状态: {0}", gameState.GetStatusDescription());
            }

            // 更新暂停按钮
            var pauseButton = this.Controls.Find("pauseButton", true).FirstOrDefault() as Button;
            if (pauseButton != null)
            {
                pauseButton.Text = gameState.Status == GameStatus.Paused ? "继续" : "暂停";
            }

            // 重绘棋盘
            boardRenderer.Invalidate();
        }

        /// <summary>
        /// 显示游戏结果
        /// </summary>
        private void ShowGameResult()
        {
            string message;
            string title;
            MessageBoxIcon icon;

            if (gameState.Status == GameStatus.Won)
            {
                message = string.Format("恭喜！您成功完成了游戏！\n\n步数: {0}\n时间: {1}", gameState.MoveCount, gameState.GetFormattedTime());
                title = "游戏胜利";
                icon = MessageBoxIcon.Information;
            }
            else
            {
                message = "游戏结束，您没有在规定步数内完成游戏。";
                title = "游戏失败";
                icon = MessageBoxIcon.Warning;
            }

            MessageBox.Show(message, title, MessageBoxButtons.OK, icon);
        }

        /// <summary>
        /// 暂停按钮点击事件
        /// </summary>
        private void PauseButton_Click(object sender, EventArgs e)
        {
            if (gameState.Status == GameStatus.Playing)
            {
                gameState.PauseGame();
                gameTimer.Stop();
            }
            else if (gameState.Status == GameStatus.Paused)
            {
                gameState.ResumeGame();
                gameTimer.Start();
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 重新开始按钮点击事件
        /// </summary>
        private void RestartButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要重新开始游戏吗？", "确认", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                gameState.RestartGame();
                gameTimer.Start();
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 撤销按钮点击事件
        /// </summary>
        private void UndoButton_Click(object sender, EventArgs e)
        {
            if (gameState.UndoMove())
            {
                MessageBox.Show("已撤销上一步操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("无法撤销，没有可撤销的操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 提示按钮点击事件
        /// </summary>
        private void HintButton_Click(object sender, EventArgs e)
        {
            if (gameState.UseHint())
            {
                var hint = gameState.GetHint();
                if (hint != null)
                {
                    // 高亮显示建议移动的方块
                    gameState.GameBoard.DeselectBlock();
                    gameState.GameBoard.SelectBlock(hint.Block.X, hint.Block.Y);
                    
                    // 显示提示信息
                    MessageBox.Show(hint.Description, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("无法提供提示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("提示次数已用完", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private void SaveButton_Click(object sender, EventArgs e)
        {
            var saveName = string.Format("存档_{0}", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            if (GameDataService.SaveGame(gameState, saveName))
            {
                MessageBox.Show("游戏保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 返回主菜单按钮点击事件
        /// </summary>
        private void MenuButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要返回主菜单吗？当前游戏进度将丢失。", "确认", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.Close();
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 窗体激活事件
        /// </summary>
        private void GameForm_Activated(object sender, EventArgs e)
        {
            // 确保窗体获得焦点以接收键盘事件
            this.Focus();
            Console.WriteLine("窗体激活，焦点设置");
            
            // 延迟一点时间再次确保焦点
            Timer focusTimer = new Timer();
            focusTimer.Interval = 100;
            focusTimer.Tick += (s, args) => 
            {
                this.Focus();
                Console.WriteLine("窗体激活延迟焦点设置完成");
                focusTimer.Stop();
                focusTimer.Dispose();
            };
            focusTimer.Start();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void GameForm_Load(object sender, EventArgs e)
        {
            // 确保窗体获得焦点以接收键盘事件
            this.Focus();
            
            // 延迟一点时间再次确保焦点和键盘事件设置
            Timer loadTimer = new Timer();
            loadTimer.Interval = 200;
            loadTimer.Tick += (s, args) =>
            {
                this.Focus();
                this.KeyPreview = true;
                Console.WriteLine("窗体加载完成，焦点设置完成");
                loadTimer.Stop();
                loadTimer.Dispose();
            };
            loadTimer.Start();
        }

        /// <summary>
        /// 窗体大小改变事件
        /// </summary>
        private void GameForm_Resize(object sender, EventArgs e)
        {
            // 调整棋盘渲染器的大小以适应窗口
            if (boardRenderer != null)
            {
                int availableWidth = this.ClientSize.Width - 280; // 减去右侧面板的宽度
                int availableHeight = this.ClientSize.Height - 40; // 减去边距
                
                // 保持棋盘渲染器的宽高比
                int newCellSize = Math.Min(availableWidth / GameBoard.BOARD_WIDTH, availableHeight / GameBoard.BOARD_HEIGHT);
                newCellSize = Math.Max(newCellSize, 40); // 最小单元格大小
                
                int boardWidth = newCellSize * GameBoard.BOARD_WIDTH + 40; // 加上边距
                int boardHeight = newCellSize * GameBoard.BOARD_HEIGHT + 40;
                
                boardRenderer.Size = new Size(boardWidth, boardHeight);
                boardRenderer.UpdateCellSize(newCellSize);
                
                // 重绘棋盘
                boardRenderer.Invalidate();
            }
        }

        /// <summary>
        /// 键盘事件
        /// </summary>
        private void GameForm_KeyDown(object sender, KeyEventArgs e)
        {
            // 添加调试信息
            Console.WriteLine(string.Format("键盘事件触发: {0}", e.KeyCode));
            Console.WriteLine(string.Format("当前焦点控件: {0}", this.ActiveControl != null ? this.ActiveControl.Name : "窗体"));
            Console.WriteLine(string.Format("窗体焦点: {0}", this.Focused));
            Console.WriteLine(string.Format("KeyPreview: {0}", this.KeyPreview));
            Console.WriteLine(string.Format("游戏状态: {0}", gameState.Status));
            Console.WriteLine(string.Format("窗体模态: {0}", this.Modal));
            
            // 测试：让所有按键都有反应
            if (e.KeyCode == Keys.Space)
            {
                Console.WriteLine("空格键被按下 - 测试键盘事件工作正常");
                MessageBox.Show("空格键被按下 - 键盘事件工作正常！", "测试", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            // 测试：让Enter键也有反应
            if (e.KeyCode == Keys.Enter)
            {
                Console.WriteLine("Enter键被按下 - 测试键盘事件工作正常");
                MessageBox.Show("Enter键被按下 - 键盘事件工作正常！", "测试", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            if (gameState.Status != GameStatus.Playing)
            {
                Console.WriteLine("游戏状态不是Playing，忽略键盘事件");
                return;
            }

            var selectedBlock = gameState.GameBoard.SelectedBlock;
            if (selectedBlock == null)
            {
                Console.WriteLine("没有选中的方块，忽略键盘事件");
                return;
            }

            Console.WriteLine(string.Format("当前选中方块: {0} 位置: ({1}, {2})", selectedBlock.Name, selectedBlock.X, selectedBlock.Y));

            int newX = selectedBlock.X;
            int newY = selectedBlock.Y;

            switch (e.KeyCode)
            {
                case Keys.Left:
                    newX--;
                    Console.WriteLine(string.Format("尝试向左移动: ({0}, {1})", newX, newY));
                    break;
                case Keys.Right:
                    newX++;
                    Console.WriteLine(string.Format("尝试向右移动: ({0}, {1})", newX, newY));
                    break;
                case Keys.Up:
                    newY--;
                    Console.WriteLine(string.Format("尝试向上移动: ({0}, {1})", newX, newY));
                    break;
                case Keys.Down:
                    newY++;
                    Console.WriteLine(string.Format("尝试向下移动: ({0}, {1})", newX, newY));
                    break;
                default:
                    return;
            }

            if (gameState.GameBoard.MoveSelectedBlock(newX, newY))
            {
                Console.WriteLine("移动成功");
                gameState.RecordMove();
            }
            else
            {
                Console.WriteLine("移动失败");
            }
            
            // 确保窗体重新获得焦点
            this.Focus();
        }

        /// <summary>
        /// 移动选中的方块
        /// </summary>
        private void MoveSelectedBlock(int deltaX, int deltaY)
        {
            if (gameState.Status != GameStatus.Playing)
            {
                Console.WriteLine("游戏状态不是Playing，忽略移动操作");
                return;
            }

            var selectedBlock = gameState.GameBoard.SelectedBlock;
            if (selectedBlock == null)
            {
                Console.WriteLine("没有选中的方块，忽略移动操作");
                return;
            }

            Console.WriteLine(string.Format("当前选中方块: {0} 位置: ({1}, {2})", selectedBlock.Name, selectedBlock.X, selectedBlock.Y));

            int newX = selectedBlock.X + deltaX;
            int newY = selectedBlock.Y + deltaY;

            Console.WriteLine(string.Format("尝试移动: ({0}, {1})", newX, newY));

            if (gameState.GameBoard.MoveSelectedBlock(newX, newY))
            {
                Console.WriteLine("移动成功");
                gameState.RecordMove();
            }
            else
            {
                Console.WriteLine("移动失败");
            }
            
            // 确保窗体重新获得焦点
            this.Focus();
        }

        /// <summary>
        /// 自动演示按钮点击事件
        /// </summary>
        private void DemoButton_Click(object sender, EventArgs e)
        {
            if (isDemoRunning)
            {
                StopDemo();
                return;
            }

            if (MessageBox.Show("是否开始自动演示？演示过程中将自动移动方块。", "自动演示", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                StartDemo();
            }
            
            // 点击后确保窗体获得焦点
            this.Focus();
        }

        /// <summary>
        /// 开始自动演示
        /// </summary>
        private void StartDemo()
        {
            if (isDemoRunning) return;

            // 生成演示步骤
            demoSteps = GenerateDemoSteps();
            if (demoSteps == null || demoSteps.Count == 0)
            {
                MessageBox.Show("无法生成演示步骤，请检查当前布局是否可解。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            currentDemoStep = 0;
            isDemoRunning = true;

            // 创建演示定时器
            demoTimer = new Timer();
            demoTimer.Interval = 1000; // 1秒执行一步
            demoTimer.Tick += DemoTimer_Tick;
            demoTimer.Start();

            // 更新按钮文本
            var demoButton = this.Controls.Find("demoButton", true).FirstOrDefault() as Button;
            if (demoButton != null)
            {
                demoButton.Text = "停止演示";
                demoButton.BackColor = Color.LightCoral;
            }

            MessageBox.Show(string.Format("开始自动演示，共{0}步。", demoSteps.Count), "演示开始", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 停止自动演示
        /// </summary>
        private void StopDemo()
        {
            if (!isDemoRunning) return;

            isDemoRunning = false;
            if (demoTimer != null)
            {
                demoTimer.Stop();
                demoTimer.Dispose();
                demoTimer = null;
            }

            // 更新按钮文本
            var demoButton = this.Controls.Find("demoButton", true).FirstOrDefault() as Button;
            if (demoButton != null)
            {
                demoButton.Text = "自动演示";
                demoButton.BackColor = Color.LightGoldenrodYellow;
            }

            MessageBox.Show("演示已停止。", "演示结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 演示定时器事件
        /// </summary>
        private void DemoTimer_Tick(object sender, EventArgs e)
        {
            if (!isDemoRunning || currentDemoStep >= demoSteps.Count)
            {
                StopDemo();
                return;
            }

            var step = demoSteps[currentDemoStep];
            
            // 选择要移动的方块
            gameState.GameBoard.DeselectBlock();
            gameState.GameBoard.SelectBlock(step.BlockX, step.BlockY);
            
            // 计算移动方向
            int deltaX = step.NewX - step.BlockX;
            int deltaY = step.NewY - step.BlockY;
            
            // 通过调用方向按钮的点击事件来移动方块
            if (deltaX == -1 && deltaY == 0)
            {
                // 向左移动
                var leftButton = this.Controls.Find("leftButton", true).FirstOrDefault() as Button;
                if (leftButton != null)
                {
                    leftButton.PerformClick();
                }
            }
            else if (deltaX == 1 && deltaY == 0)
            {
                // 向右移动
                var rightButton = this.Controls.Find("rightButton", true).FirstOrDefault() as Button;
                if (rightButton != null)
                {
                    rightButton.PerformClick();
                }
            }
            else if (deltaX == 0 && deltaY == -1)
            {
                // 向上移动
                var upButton = this.Controls.Find("upButton", true).FirstOrDefault() as Button;
                if (upButton != null)
                {
                    upButton.PerformClick();
                }
            }
            else if (deltaX == 0 && deltaY == 1)
            {
                // 向下移动
                var downButton = this.Controls.Find("downButton", true).FirstOrDefault() as Button;
                if (downButton != null)
                {
                    downButton.PerformClick();
                }
            }
            
            Console.WriteLine(string.Format("演示步骤 {0}: 尝试移动方块 ({1}, {2}) -> ({3}, {4})", 
                currentDemoStep + 1, step.BlockX, step.BlockY, step.NewX, step.NewY));

            currentDemoStep++;
            
            // 检查是否完成
            if (gameState.GameBoard.IsGameWon())
            {
                StopDemo();
                MessageBox.Show("演示完成！游戏已胜利。", "演示完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 生成演示步骤
        /// </summary>
        private List<MoveStep> GenerateDemoSteps()
        {
            // 使用A*搜索算法找到解决方案
            var solution = FindSolution();
            if (solution != null && solution.Count > 0)
            {
                Console.WriteLine(string.Format("找到解决方案，共 {0} 步", solution.Count));
                return solution;
            }
            
            // 如果找不到完整解决方案，使用启发式算法生成部分步骤
            Console.WriteLine("未找到完整解决方案，使用启发式算法");
            return GenerateHeuristicSteps();
        }
        
        /// <summary>
        /// 使用A*搜索算法找到解决方案
        /// </summary>
        private List<MoveStep> FindSolution()
        {
            var initialState = new GameStateNode(gameState.GameBoard);
            var openSet = new List<GameStateNode> { initialState };
            var closedSet = new HashSet<string>();
            var cameFrom = new Dictionary<string, GameStateNode>();
            var gScore = new Dictionary<string, int> { { initialState.GetHash(), 0 } };
            var fScore = new Dictionary<string, int> { { initialState.GetHash(), Heuristic(initialState) } };
            
            while (openSet.Count > 0)
            {
                // 找到fScore最小的节点
                var current = openSet.OrderBy(n => 
                {
                    int score;
                    return fScore.TryGetValue(n.GetHash(), out score) ? score : int.MaxValue;
                }).First();
                
                // 检查是否达到目标状态
                if (IsGoalState(current))
                {
                    return ReconstructPath(cameFrom, current);
                }
                
                openSet.Remove(current);
                closedSet.Add(current.GetHash());
                
                // 生成所有可能的移动
                var neighbors = GenerateNeighbors(current);
                foreach (var neighbor in neighbors)
                {
                    if (closedSet.Contains(neighbor.GetHash()))
                        continue;
                    
                    int currentGScore;
                    gScore.TryGetValue(current.GetHash(), out currentGScore);
                    var tentativeGScore = currentGScore + 1;
                    
                    if (!openSet.Any(n => n.GetHash() == neighbor.GetHash()))
                        openSet.Add(neighbor);
                    else 
                    {
                        int neighborGScore;
                        gScore.TryGetValue(neighbor.GetHash(), out neighborGScore);
                        if (tentativeGScore >= neighborGScore)
                            continue;
                    }
                    
                    cameFrom[neighbor.GetHash()] = current;
                    gScore[neighbor.GetHash()] = tentativeGScore;
                    fScore[neighbor.GetHash()] = tentativeGScore + Heuristic(neighbor);
                }
                
                // 限制搜索深度，避免无限搜索
                if (openSet.Count > 1000)
                {
                    Console.WriteLine("搜索空间过大，停止搜索");
                    break;
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 启发式算法生成部分步骤
        /// </summary>
        private List<MoveStep> GenerateHeuristicSteps()
        {
            var steps = new List<MoveStep>();
            var blocks = gameState.GameBoard.Blocks.ToList();
            var random = new Random();
            
            // 尝试生成4-8步有效的移动
            int targetSteps = random.Next(4, 9);
            int maxAttempts = 200;
            int attempts = 0;
            
            while (steps.Count < targetSteps && attempts < maxAttempts)
            {
                attempts++;
                
                // 智能选择方块：优先选择小方块和边缘方块
                Block selectedBlock = SelectSmartBlock(blocks, random);
                var currentX = selectedBlock.X;
                var currentY = selectedBlock.Y;
                
                // 智能选择移动方向：优先选择朝向出口的方向
                var direction = SelectSmartDirection(selectedBlock, random);
                int newX = currentX + direction[0];
                int newY = currentY + direction[1];
                
                // 检查新位置是否在棋盘范围内
                if (newX >= 0 && newX <= GameBoard.BOARD_WIDTH - selectedBlock.Width &&
                    newY >= 0 && newY <= GameBoard.BOARD_HEIGHT - selectedBlock.Height)
                {
                    // 检查是否可以移动到新位置
                    if (gameState.GameBoard.CanMoveBlock(selectedBlock, newX, newY))
                    {
                        // 额外检查：避免移动到死胡同
                        if (!IsDeadEnd(selectedBlock, newX, newY))
                        {
                            steps.Add(new MoveStep
                            {
                                BlockX = currentX,
                                BlockY = currentY,
                                NewX = newX,
                                NewY = newY
                            });
                            
                            Console.WriteLine(string.Format("找到启发式移动: 方块 {0} 从 ({1}, {2}) 移动到 ({3}, {4})", 
                                selectedBlock.Name, currentX, currentY, newX, newY));
                        }
                    }
                }
            }
            
            Console.WriteLine(string.Format("生成启发式步骤完成，共找到 {0} 个移动", steps.Count));
            return steps;
        }
        
        /// <summary>
        /// 智能选择方块：优先选择小方块和边缘方块
        /// </summary>
        private Block SelectSmartBlock(List<Block> blocks, Random random)
        {
            // 按优先级排序方块
            var sortedBlocks = blocks.OrderBy(b => 
            {
                int priority = 0;
                
                // 优先选择小方块（1x1或1x2）
                if (b.Width == 1 && b.Height == 1) priority += 10;
                else if ((b.Width == 1 && b.Height == 2) || (b.Width == 2 && b.Height == 1)) priority += 8;
                else if (b.Width == 2 && b.Height == 2) priority += 6;
                else priority += 4;
                
                // 优先选择边缘方块
                if (b.X == 0 || b.X + b.Width == GameBoard.BOARD_WIDTH || 
                    b.Y == 0 || b.Y + b.Height == GameBoard.BOARD_HEIGHT)
                {
                    priority += 5;
                }
                
                // 优先选择靠近出口的方块（底部）
                priority += (GameBoard.BOARD_HEIGHT - b.Y - b.Height) * 2;
                
                return priority;
            }).ToList();
            
            // 从前3个优先级最高的方块中随机选择
            int selectIndex = random.Next(Math.Min(3, sortedBlocks.Count));
            return sortedBlocks[selectIndex];
        }
        
        /// <summary>
        /// 智能选择移动方向：优先选择朝向出口的方向
        /// </summary>
        private int[] SelectSmartDirection(Block block, Random random)
        {
            var directions = new List<int[]>
            {
                new int[] { -1, 0 },  // 左
                new int[] { 1, 0 },   // 右
                new int[] { 0, -1 },  // 上
                new int[] { 0, 1 }    // 下
            };
            
            // 计算每个方向的权重
            var weightedDirections = new List<Tuple<int[], int>>();
            
            foreach (var direction in directions)
            {
                int weight = 1; // 基础权重
                
                // 优先向下移动（朝向出口）
                if (direction[1] == 1) weight += 3;
                // 其次向左移动（通常出口在左侧）
                else if (direction[0] == -1) weight += 2;
                // 再次向右移动
                else if (direction[0] == 1) weight += 1;
                // 向上移动权重最低
                else weight += 0;
                
                weightedDirections.Add(new Tuple<int[], int>(direction, weight));
            }
            
            // 按权重随机选择
            int totalWeight = weightedDirections.Sum(t => t.Item2);
            int randomValue = random.Next(totalWeight);
            int currentWeight = 0;
            
            foreach (var item in weightedDirections)
            {
                currentWeight += item.Item2;
                if (randomValue < currentWeight)
                {
                    return item.Item1;
                }
            }
            
            // 默认返回第一个方向
            return directions[0];
        }
        
        /// <summary>
        /// 检查是否是死胡同
        /// </summary>
        private bool IsDeadEnd(Block block, int newX, int newY)
        {
            // 简单的死胡同检测：检查移动后是否完全被包围
            int surroundedSides = 0;
            
            // 检查四个方向是否被阻挡
            if (newX <= 0 || !CanMoveTo(block, newX - 1, newY)) surroundedSides++;
            if (newX + block.Width >= GameBoard.BOARD_WIDTH || !CanMoveTo(block, newX + 1, newY)) surroundedSides++;
            if (newY <= 0 || !CanMoveTo(block, newX, newY - 1)) surroundedSides++;
            if (newY + block.Height >= GameBoard.BOARD_HEIGHT || !CanMoveTo(block, newX, newY + 1)) surroundedSides++;
            
            // 如果被3个或更多方向阻挡，认为是死胡同
            return surroundedSides >= 3;
        }
        
        /// <summary>
        /// 检查方块是否可以移动到指定位置
        /// </summary>
        private bool CanMoveTo(Block block, int newX, int newY)
        {
            // 检查边界
            if (newX < 0 || newY < 0 || 
                newX + block.Width > GameBoard.BOARD_WIDTH || 
                newY + block.Height > GameBoard.BOARD_HEIGHT)
            {
                return false;
            }
            
            // 检查与其他方块的碰撞
            foreach (var otherBlock in gameState.GameBoard.Blocks)
            {
                if (otherBlock != block && otherBlock.X < newX + block.Width && 
                    otherBlock.X + otherBlock.Width > newX &&
                    otherBlock.Y < newY + block.Height && 
                    otherBlock.Y + otherBlock.Height > newY)
                {
                    return false;
                }
            }
            
            return true;
        }
        
        /// <summary>
        /// 启发式函数：计算到目标状态的距离
        /// </summary>
        private int Heuristic(GameStateNode node)
        {
            // 找到曹操方块
            var caoBlock = node.Blocks.FirstOrDefault(b => b.IsCaoCao);
            if (caoBlock == null) return 0;
            
            // 计算曹操到出口的距离
            int distanceToExit = Math.Abs(caoBlock.X - 1) + Math.Abs(caoBlock.Y - 3);
            
            // 计算所有方块到理想位置的距离
            int totalDistance = 0;
            foreach (var block in node.Blocks)
            {
                if (block.IsCaoCao)
                {
                    // 曹操应该在(1,3)位置
                    totalDistance += Math.Abs(block.X - 1) + Math.Abs(block.Y - 3);
                }
                else if (block.Width == 2 && block.Height == 1)
                {
                    // 大将应该在顶部
                    totalDistance += Math.Abs(block.Y - 0);
                }
                else if (block.Width == 1 && block.Height == 2)
                {
                    // 中军应该在两侧
                    totalDistance += Math.Abs(block.X - 0) + Math.Abs(block.X - 3);
                }
            }
            
            return distanceToExit * 10 + totalDistance;
        }
        
        /// <summary>
        /// 检查是否达到目标状态
        /// </summary>
        private bool IsGoalState(GameStateNode node)
        {
            // 找到曹操方块
            var caoBlock = node.Blocks.FirstOrDefault(b => b.IsCaoCao);
            if (caoBlock == null) return false;
            
            // 曹操应该在(1,3)位置，即出口位置
            return caoBlock.X == 1 && caoBlock.Y == 3;
        }
        
        /// <summary>
        /// 生成所有可能的邻居状态
        /// </summary>
        private List<GameStateNode> GenerateNeighbors(GameStateNode node)
        {
            var neighbors = new List<GameStateNode>();
            
            foreach (var block in node.Blocks)
            {
                // 尝试四个方向的移动
                int[][] directions = { 
                    new int[] { -1, 0 },  // 左
                    new int[] { 1, 0 },   // 右
                    new int[] { 0, -1 },  // 上
                    new int[] { 0, 1 }    // 下
                };
                
                foreach (var direction in directions)
                {
                    int newX = block.X + direction[0];
                    int newY = block.Y + direction[1];
                    
                    // 检查是否可以移动
                    if (CanMoveBlockInState(node, block, newX, newY))
                    {
                        var move = new MoveStep
                        {
                            BlockX = block.X,
                            BlockY = block.Y,
                            NewX = newX,
                            NewY = newY
                        };
                        
                        neighbors.Add(new GameStateNode(node, move));
                    }
                }
            }
            
            return neighbors;
        }
        
        /// <summary>
        /// 在指定状态下检查方块是否可以移动
        /// </summary>
        private bool CanMoveBlockInState(GameStateNode state, Block block, int newX, int newY)
        {
            // 检查边界
            if (newX < 0 || newY < 0 || 
                newX + block.Width > GameBoard.BOARD_WIDTH || 
                newY + block.Height > GameBoard.BOARD_HEIGHT)
            {
                return false;
            }
            
            // 检查与其他方块的碰撞
            foreach (var otherBlock in state.Blocks)
            {
                if (otherBlock != block && otherBlock.X < newX + block.Width && 
                    otherBlock.X + otherBlock.Width > newX &&
                    otherBlock.Y < newY + block.Height && 
                    otherBlock.Y + otherBlock.Height > newY)
                {
                    return false;
                }
            }
            
            return true;
        }
        
        /// <summary>
        /// 重建路径
        /// </summary>
        private List<MoveStep> ReconstructPath(Dictionary<string, GameStateNode> cameFrom, GameStateNode current)
        {
            var path = new List<MoveStep>();
            
            while (current != null && current.LastMove != null)
            {
                path.Insert(0, current.LastMove);
                GameStateNode parent;
                cameFrom.TryGetValue(current.GetHash(), out parent);
                current = parent;
            }
            
            return path;
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (gameTimer != null)
            {
                gameTimer.Stop();
            }
            if (demoTimer != null)
            {
                demoTimer.Stop();
                demoTimer.Dispose();
            }
            // if (focusTimer != null)
            // {
            //     focusTimer.Stop();
            // }
            gameState.StateChanged -= GameState_StateChanged;
            base.OnFormClosing(e);
        }
    }

    /// <summary>
    /// 移动步骤类
    /// </summary>
    public class MoveStep
    {
        public int BlockX { get; set; }
        public int BlockY { get; set; }
        public int NewX { get; set; }
        public int NewY { get; set; }
    }
    
    /// <summary>
    /// 游戏状态节点类（用于A*搜索）
    /// </summary>
    public class GameStateNode
    {
        public List<Block> Blocks { get; set; }
        public MoveStep LastMove { get; set; }
        
        public GameStateNode(GameBoard board)
        {
            Blocks = board.Blocks.Select(b => new Block(
                b.Id, b.Name, b.Width, b.Height, b.X, b.Y, b.Color, b.IsCaoCao
            )).ToList();
        }
        
        public GameStateNode(GameStateNode parent, MoveStep move)
        {
            Blocks = parent.Blocks.Select(b => new Block(
                b.Id, b.Name, b.Width, b.Height, b.X, b.Y, b.Color, b.IsCaoCao
            )).ToList();
            
            // 应用移动
            var block = Blocks.FirstOrDefault(b => b.X == move.BlockX && b.Y == move.BlockY);
            if (block != null)
            {
                block.X = move.NewX;
                block.Y = move.NewY;
            }
            
            LastMove = move;
        }
        
        public string GetHash()
        {
            var sb = new StringBuilder();
            foreach (var block in Blocks.OrderBy(b => b.Name))
            {
                sb.AppendFormat("{0}:{1},{2};", block.Name, block.X, block.Y);
            }
            return sb.ToString();
        }
    }

    /// <summary>
    /// 游戏棋盘渲染器
    /// </summary>
    public class GameBoardRenderer : Control
    {
        private GameBoard gameBoard;
        private int cellSize = 80;
        private int boardMargin = 20;

        public GameBoardRenderer(GameBoard gameBoard)
        {
            this.gameBoard = gameBoard;
            this.DoubleBuffered = true;
            this.TabStop = false;
            
            // 设置鼠标事件
            this.MouseDown += GameBoardRenderer_MouseDown;
            this.MouseMove += GameBoardRenderer_MouseMove;
            this.MouseUp += GameBoardRenderer_MouseUp;
        }

        /// <summary>
        /// 更新单元格大小
        /// </summary>
        public void UpdateCellSize(int newCellSize)
        {
            this.cellSize = newCellSize;
            this.boardMargin = newCellSize / 4; // 边距为单元格大小的1/4
        }

        /// <summary>
        /// 鼠标按下事件
        /// </summary>
        private void GameBoardRenderer_MouseDown(object sender, MouseEventArgs e)
        {
            var boardX = (e.X - boardMargin) / cellSize;
            var boardY = (e.Y - boardMargin) / cellSize;
            
            if (boardX >= 0 && boardX < GameBoard.BOARD_WIDTH && 
                boardY >= 0 && boardY < GameBoard.BOARD_HEIGHT)
            {
                gameBoard.SelectBlock(boardX, boardY);
                this.Invalidate();
                
                // 确保父窗体获得焦点以接收键盘事件
                if (this.Parent != null)
                {
                    this.Parent.Focus();
                }
            }
        }

        /// <summary>
        /// 鼠标移动事件
        /// </summary>
        private void GameBoardRenderer_MouseMove(object sender, MouseEventArgs e)
        {
            // 这里可以实现拖拽功能
        }

        /// <summary>
        /// 鼠标释放事件
        /// </summary>
        private void GameBoardRenderer_MouseUp(object sender, MouseEventArgs e)
        {
            // 这里可以实现拖拽功能
        }

        /// <summary>
        /// 绘制控件
        /// </summary>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            var g = e.Graphics;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            // 绘制背景
            g.Clear(Color.White);

            // 绘制棋盘网格
            DrawGrid(g);

            // 绘制方块
            DrawBlocks(g);
        }

        /// <summary>
        /// 绘制网格
        /// </summary>
        private void DrawGrid(Graphics g)
        {
            var pen = new Pen(Color.LightGray, 1);
            
            // 绘制垂直线
            for (int x = 0; x <= GameBoard.BOARD_WIDTH; x++)
            {
                int xPos = boardMargin + x * cellSize;
                g.DrawLine(pen, xPos, boardMargin, xPos, boardMargin + GameBoard.BOARD_HEIGHT * cellSize);
            }
            
            // 绘制水平线
            for (int y = 0; y <= GameBoard.BOARD_HEIGHT; y++)
            {
                int yPos = boardMargin + y * cellSize;
                g.DrawLine(pen, boardMargin, yPos, boardMargin + GameBoard.BOARD_WIDTH * cellSize, yPos);
            }
        }

        /// <summary>
        /// 绘制方块
        /// </summary>
        private void DrawBlocks(Graphics g)
        {
            foreach (var block in gameBoard.Blocks)
            {
                var rect = new Rectangle(
                    boardMargin + block.X * cellSize,
                    boardMargin + block.Y * cellSize,
                    block.Width * cellSize,
                    block.Height * cellSize
                );

                // 绘制方块背景
                var brush = new SolidBrush(block.Color);
                g.FillRectangle(brush, rect);

                // 绘制边框
                var pen = new Pen(Color.Black, 2);
                g.DrawRectangle(pen, rect);

                // 如果方块被选中，绘制选中效果
                if (block.IsSelected)
                {
                    var selectionPen = new Pen(Color.Yellow, 3);
                    g.DrawRectangle(selectionPen, rect);
                }

                // 绘制方块名称
                var font = new Font("微软雅黑", 8, FontStyle.Bold);
                var textBrush = new SolidBrush(Color.Black);
                var textSize = g.MeasureString(block.Name, font);
                var textX = rect.X + (rect.Width - textSize.Width) / 2;
                var textY = rect.Y + (rect.Height - textSize.Height) / 2;
                g.DrawString(block.Name, font, textBrush, textX, textY);
            }
        }
    }
} 